package com.zang.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;

/**
 * excel工具类
 * @author mxl
 */
public class ExcelUtil {

    /**
     * 是否是2003的excel，返回true是2003
     */

    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    /**
     *  是否是2007的excel，返回true是2007
     */

    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /**
     * 验证EXCEL文件
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath){
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){
            return false;
        }
        return true;
    }

    /**
     * 创建Workbook
     *
     * @param is
     * @param fileName
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbook(InputStream is, String fileName) throws IOException {
        Workbook wb = null;
        if (ExcelUtil.isExcel2007(fileName)) {
            wb = new XSSFWorkbook(is);
        } else {
            wb = new HSSFWorkbook(is);
        }
        return wb;
    }

}
